#include "COSM.h"

COSM::COSM(GSM& gsm, TR tr1, TR tr2) : 
Controller("L"),
_gsm(gsm) ,
_tr1(tr1),
_tr2(tr2) {

  _cosmPeriodMinutes = 15;
  _lastCosmTs = millis() - _cosmPeriodMinutes * 60000;
}

void COSM::setCommand(String command) {
  if(command.equalsIgnoreCase("OFF")) {
    _cosmPeriodMinutes = -1;
  } 
  else {
    _cosmPeriodMinutes = command.toInt();
  }
}

boolean COSM::check() {
  if(_cosmPeriodMinutes <= 0) {
    return false;
  }
  _currTs = millis();
  if(_currTs < _lastCosmTs) {
      _lastCosmTs = 0;
  }
  
  //Serial.println(String("if(") + _currTs + " > " + _lastCosmTs + " + " + (_cosmPeriodMinutes * 60000) + ") = " + (_currTs > _lastCosmTs + _cosmPeriodMinutes * 60000));
  if(_currTs > _lastCosmTs + _cosmPeriodMinutes * 60000) {
      _gsm.cosmConnect();
      _cosmSend("105885", _tr1.getSensor(), _tr1.getRelay());
      _cosmSend("105887", _tr2.getSensor(), _tr2.getRelay());
      _gsm.cosmDisconnect();
      _lastCosmTs = _currTs;
  }
  
  return false;
}


void COSM::_cosmSend(String feed, Sensor& s, Relay& r) {
  _gsm.cosmSend(feed, s.getTemperature(), s.getHumidity(), r.isOn(), s.getFailedAttempts());
}

String COSM::getStatus() {
  return getId() + "(P=" + _cosmPeriodMinutes + ")";
}


